package com.sunny.shop.api.v1;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.sunny.shop.core.interceptors.ScopeLevel;
import com.sunny.shop.dto.GoodsDTO;
import com.sunny.shop.exception.httpe.NotFoundException;
import com.sunny.shop.model.Good;
import com.sunny.shop.service.GoodsServiceImpl;
import com.sunny.shop.vo.GoodsSimplifyVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodController {
    @Autowired
    private GoodsServiceImpl goodsService;

    @GetMapping("/list")
    public List<GoodsSimplifyVO> getGoods(){
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        List<Good> goods = this.goodsService.getGoods();
        List<GoodsSimplifyVO> vos = new ArrayList<>();
        goods.forEach(item->{
            GoodsSimplifyVO map = mapper.map(item, GoodsSimplifyVO.class);
            vos.add(map);
        });
        return vos;
    }

    @GetMapping("/{id}")
    public GoodsSimplifyVO getDetail(@PathVariable Long id){
        Good goodsDetail = this.goodsService.getGoodsDetail(id);
        if(goodsDetail == null){
            throw new NotFoundException(40000);
        }
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();
        GoodsSimplifyVO vo = mapper.map(goodsDetail, GoodsSimplifyVO.class);
        return vo;
    }

    /**
     * 积分兑换
     * @param goodsDTO
     * @return
     */
    @ScopeLevel()
    @PostMapping("")
    public HashMap<String, String> exchangeGoods(@RequestBody GoodsDTO goodsDTO){
        String orderSn = this.goodsService.exchangeGoods(goodsDTO);
        HashMap<String, String> sn = new HashMap<>();
        sn.put("order_sn", orderSn);
        return sn;
    }
}
